package me.zhengjie.domain;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.ObjectUtil;
import io.swagger.models.auth.In;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.dto.MesMessage;
import me.zhengjie.dto.sqlServer.*;
import me.zhengjie.repository.*;
import me.zhengjie.service.OutBoundOrderService;
import me.zhengjie.service.StorageService;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Slf4j
@Component
@RequiredArgsConstructor
public class TaskResultService {

    private final TaskResultRepository taskResultRepository;
    private final PalletRepository palletRepository;
    private final InBoundMissionHistoryRepository inBoundMissionHistoryRepository;
    private final StorageService storageService;
    private final InventoryRepository inventoryRepository;
    private final ProcesscardRepository processcardRepository;
    private final OutBoundMissionRepository outBoundMissionRepository;
    private final OutBoundOrderService outBoundOrderService;
    private final OutBoundMissionHistoryRepository outBoundMissionHistoryRepository;

    public TaskResult findNowTaskResult(Integer taskType) {
        return taskResultRepository.findTaskResultByWcsTaskType(taskType);
    }

    public int deleteByWcsTaskType(Integer taskType) {
        return taskResultRepository.deleteByWcsTaskType(taskType);
    }

    public int deleteByWmsTaskId(String taskId){
        return taskResultRepository.deleteTaskResultByWmsTaskId(taskId);
    }

    public void saveTaskResult(TaskResult taskResult) {
        taskResultRepository.save(taskResult);
    }

    @Transactional
    public MesMessage commitFinish(String taskId){
        MesMessage mesMessage = new MesMessage();
        TaskResult taskResult = taskResultRepository.findTaskResultByWmsTaskId(taskId.toString());
        if (ObjectUtil.isEmpty(taskResult)){
            mesMessage.setSuccessCode(400);
            mesMessage.setErrorMessage("没有找到任务资料!");
            // 获取失败
            return mesMessage;
        }else {

            Integer taskType = taskResult.getWcsTaskType();
            String wmsTaskId = taskResult.getWmsTaskId();
            // 入库任务
            if (taskType == 1){
                log.info("收到入库任务反馈，开始更新历史任务，储位，以及库存");
                // 任务结束记录
                int inBoundMissionHistoryResult = inBoundMissionHistoryRepository.updateFinishTime(DateTime.now().toTimestamp(), wmsTaskId, "任务完成");
                log.info("更新的历史入库任务条数：{}",inBoundMissionHistoryResult);
                // 释放储位
                String storageCode = taskResult.getToLocation();
                int storageResult = storageService.openStorage(storageCode);
                log.info("更新的储位条数：{}",storageResult);

                // 入库信息补全
                String palletCode = taskResult.getLpnCode();
                Pallet pallet = palletRepository.findPalletByPalletCode(palletCode);
                log.error("载盘已进入库区，当前载盘：{}",pallet);
                Integer processCardId = pallet.getProcesscardId();
                Processcard processcard = processcardRepository.findProcesscardById(processCardId);
                Storage storage = storageService.findStorageByStorageCode(storageCode);
                // 入库存
                Inventory inventory = new Inventory();
                inventory.setWorkNum(processcard.getWorkNum());
                inventory.setBatch(processcard.getProcesscardCode());
                // 入库完成时间
                inventory.setInBoundFinishTime(DateTime.now().toTimestamp());
                inventory.setInventoryStatus(1);
                inventory.setStorageId(storage.getId());
                inventory.setPalletId(pallet.getId());
                inventory.setProcesscardId(processcard.getId());
                log.info("载盘已进入库区，更新库存信息：{}",inventory);
                inventoryRepository.save(inventory);
                // 更新储位的信息
                storageService.finishInBound(pallet.getId(),storageCode);
                this.deleteByWmsTaskId(wmsTaskId);
                // 出库任务
            }
            else if (taskType == 2){
                // 查询出库单
                String missionCode = wmsTaskId;
                Integer orderId = outBoundMissionRepository.findOutBoundMissionByMissionCode(missionCode).getOutBoundOrderId();


                        /*List<OutBoundOrderDetail> details = outBoundOrderDetailRepository.findOutBoundOrderDetailsByOutBoundOrderId(orderId);
                        List<Integer> detailPalletIds = details.stream().map(OutBoundOrderDetail::getPalletId).collect(Collectors.toList());
                        log.info("查询到的出库明细单中的载盘id:{}",detailPalletIds);
                        String workNum = outBoundOrder.getWorkNum();
                        List<Inventory> inventories = inventoryRepository.findInventoriesByWorkNum(workNum);
                        log.info("查询到的该出库单工程号对应的库存：{}",inventories);*/

                List<OutBoundMission> outBoundMissions = outBoundMissionRepository.findOutBoundMissionsByOutBoundOrderId(orderId);

                if (outBoundMissions.size()==1){
                    log.info("出库单：{}{}",orderId,"结束！");
                    outBoundOrderService.finishOrder(orderId);
                }

                        /*List<Integer> inventoryPalletIds = inventories.stream().map(Inventory::getPalletId).collect(Collectors.toList());
                        int count = Math.toIntExact(detailPalletIds.stream()
                                .filter(inventoryPalletIds::contains)
                                .count());
                        if (count == 1){

                            outBoundOrderService.finishOrder(orderId);
                        }*/

                // 任务结束记录
                outBoundMissionHistoryRepository.updateFinishTime(DateTime.now().toTimestamp(), wmsTaskId,"任务完成");
                // 释放储位
                storageService.cleanStorage(taskResult.getFromLocation());

                // 删除库存
                Pallet pallet = palletRepository.findPalletByPalletCode(taskResult.getLpnCode());
                Integer palletId = pallet.getId();

                // 删除任务，库存，任务状态
                outBoundMissionRepository.deleteOutBoundMissionByMissionCode(String.valueOf(missionCode));
                inventoryRepository.deleteInventoryByPalletId(palletId);
                this.deleteByWmsTaskId(wmsTaskId);
            }
            // 操作成功
            return null;
        }
    }
}
